<template>
  <div class="clearfix">
    <a-upload
      :action="upServer"
      :headers="headers"
      accept="image/*"
      :list-type="listType || 'picture-card'"
      :file-list="fileList"
      :beforeUpload="beforeUpload"
      @preview="handlePreview"
      @change="handleChange"
      :disabled="disabled"
      :data="data"
    >
   
    <div v-if="fileList.length < count && !disabled" >
      <a-icon v-if="!listType || listType=='picture-card'" type="plus" />
      <a-button v-if="listType && listType!='picture-card'"> <a-icon type="upload" /> 上传 </a-button>
    </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>

import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import defaultSettings from '@/config/defaultSettings'
const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
}
const getDbFile=(path)=>{
  if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
  }
  return path.substring(path.indexOf(defaultSettings.sdpFiles));
}


function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name:'LImageUpload',
  props:{
    value:{
      type:String,
      required:false
    },
    form:{
      type:Object,
      default:()=>{}
    },
    field:String,
    listType:{
      type:String,
      default:'picture-card'
    },
    disabled:Boolean,
    count:{
      type:Number,
      default:100
    },
    data:{
      type:Object,
      default:()=>{}
    }
  },
  created(){
    const token = storage.get(ACCESS_TOKEN)
    this.headers = {[`${ACCESS_TOKEN}`]:token}
    this.upServer = defaultSettings.uploadServer
    this.initFileList()
    
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      headers:{},
      devServer:'',
      showUploadList:true,

    };
  },
  watch:{
    value(val){
      this.initFileList(val)
    }
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      let fileList = info.fileList
      if(info.file.status==='done'){
        if(info.file.response.success){
           fileList = fileList.map((file) => {
              if (file.response) {
                file.url = defaultSettings.fileServer+'/'+file.response.message;
                console.log(file.url)
              }
              return file;
            });
        }else{
          this.$message.error(`${info.file.name} 上传失败.`);
          return false  
        }
      }else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`);
      }else if(info.file.status === 'removed'){
        this.handleDelete(info.file)
      }
      this.fileList = fileList

      if(info.file.status==='done' || info.file.status === 'removed'){
        this.handlePathChange()
      }
    },
    beforeUpload(file){
      return true
    },
    initFileList(path){
      if(!path || path.length==0){
        this.fileList = [];
        return;
      }

      let fileList = [];
      let arr = path.split(",")
      for(var a=0;a<arr.length;a++){
        fileList.push({
            uid:uidGenerator(),
            name:getFileName(arr[a]),
            status: 'done',
            url: defaultSettings.fileServer+'/'+arr[a],
            
        })
      }
      this.fileList = fileList
    },
    handleDelete(file){
      //文件删除
      console.log(file)
      
            
    },
    handlePathChange(){
      let uploadFiles = this.fileList
      let path = ''
      if(!uploadFiles || uploadFiles.length==0){
        path = ''
      }
      let arr = [];
      for(var a=0;a<uploadFiles.length;a++){
       arr.push(getDbFile(uploadFiles[a].url))
      }
      if(arr.length>0){
        path = arr.join(",")
      }
      //更新值
      this.form.setFieldsValue({[`${this.field}`]: path})
    }
  },
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.ant-upload-picture-card-wrapper {
  max-height:200px;overflow:auto;
}
.ant-upload-list-text {
  max-height:200px;overflow:auto;
}
.ant-upload-list-picture{
  max-height:200px;overflow:auto;
}
</style>